<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        style="display: none;"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['id']"/>
      </a-form-item>

      <a-form-item
        label="主机分组"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-tree-select
          v-decorator="['group', {rules: [{ required: true, message: '请选择主机分组！' }]}]"
          style="width: 100%"
          :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
          :treeData="groupTree"
          placeholder="请选择主机分组"
          treeDefaultExpandAll
        >
                  <span slot="title" slot-scope="{ id }">{{ id }}
                  </span>
        </a-tree-select>
      </a-form-item>

      <a-form-item
        label="主机名称"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        has-feedback
      >
        <a-input placeholder="请输入主机名称" v-decorator="['hostname', {rules: [{required: true, message: '请输入主机名称！'}]}]"/>
      </a-form-item>

      <a-form-item
        label="连接地址"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-row>
          <a-col :md="7" :sm="24">
            <a-input addon-before="ssh" placeholder="用户名"
                     v-decorator="['username', {rules: [{required: true}]}]"/>
          </a-col>
          <a-col :md="10" :sm="24">
            <a-input addon-before="@" placeholder="主机名/ip"
                     v-decorator="['ip', {rules: [{required: true}]}]"/>
          </a-col>
          <a-col :md="7" :sm="24">
            <a-input addon-before="-p" placeholder="端口"
                     v-decorator="['port', {rules: [{required: true}]}]"/>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item
        label="独立密钥"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        extra="默认使用全局密钥，如果上传了独立密钥则优先使用该密钥。"
        has-feedback
      >
        <a-textarea :auto-size="{ minRows: 2, maxRows: 11 }" placeholder="请输入独立密钥"
                    v-decorator="['pkey', {rules: [{required: false}]}]"/>
      </a-form-item>

      <a-form-item
        label="备注"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-textarea placeholder="请输入备注" :rows="2" v-decorator="['desc', {rules: [{required: false}]}]"/>
      </a-form-item>
      <a-form-item
        :wrapperCol="infoWrapperCol"
      >
        <a-alert
          description="首次验证时需要输入登录用户名对应的密码，该密码会用于配置密钥连接，不会存储该密码。"
          type="info"
          show-icon
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script type="text/jsx">
  import * as groupApi from '@/api/main/group'
  import * as api from '@/api/main/host'
  // 导入提示信息字典
  import config from '@/config/dict'

  export default {
    name: 'sForm',
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        infoWrapperCol: {
          xs: { span: 24 },
          sm: { span: 15, offset: 5 }
        },
        visible: false,
        title: '',
        groupTree: [],
        group: '',
        form: this.$form.createForm(this)
      }
    },
    methods: {
      // 初始化方法
      open(record) {
        this.getGroupTree()
        this.visible = true
        if (record) {
          this.title = '编辑主机'
          setTimeout(() => {
            this.setUserItem(record)
          }, 100)
        } else {
          this.title = '新增主机'
        }
      },
      setUserItem(record) {
        this.form.setFieldsValue(
          {
            id: record.id,
            group: record.group,
            hostname: record.hostname,
            username: record.username,
            ip: record.ip,
            port: record.port,
            pkey: record.pkey,
            desc: record.desc
          }
        )
      },
      getGroupTree() {
        /**
         * 获取到主机分组，展开顶级下树节点，考虑到后期数据量变大，不建议全部展开
         */
        groupApi.getList().then(res => {
          this.groupTree = res.data.data
        })
      },
      // [确认按钮]提交数据方法
      handleSubmit() {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            if (values.id) {
              this.message = config.msgDict[1]
              api.updateObj(values).then((res) => {
                this._handle_response(res, values)
              })
            } else {
              this.message = config.msgDict[0]
              api.addObj(values).then((res) => {
                this._handle_response(res, values)
              })
            }
          }
        })
      },
      _handle_response(res, values) {
        if (res.success) {
          this.$message.success(this.message['success'])
          this.$emit('ok', values)
          this.handleCancel()
        } else {
          this.$message.error(this.message['failed'] + res.message)
        }
      },
      // [取消按钮]重置数据,关闭弹框
      handleCancel() {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
